import 'package:flutter/material.dart';
import 'package:flutter_json_view/flutter_json_view.dart';
import 'package:flutter_redis/controller/theme_controller.dart';
import 'package:flutter_redis/pages/redis_query_page_controller.dart';
import 'package:flutter_redis/routes/routes.dart';
import 'package:get/get.dart';
import '../controller/redis_controller.dart';
import 'redis_config_page.dart';

class RedisQueryPage extends StatelessWidget {
  RedisQueryPage({super.key});
  final _redisController = Get.find<RedisController>();
  final ThemeController themeController = Get.put(ThemeController());
  final TextEditingController _searchController = TextEditingController();

  @override
  Widget build(BuildContext context) {
    final RedisQueryPageController controller = Get.put(
      RedisQueryPageController(),
    );

    final config = Get.arguments;
    if (config != null &&
        _redisController.currentConfig.value?.id != config.id) {
      _redisController.currentConfig.value = config;
    }

    void search() {
      if (_searchController.text.isNotEmpty) {
        _redisController.searchKeys(_searchController.text);
      }
    }

    return Scaffold(
      appBar: AppBar(
        title: Obx(
          () => Text(_redisController.currentConfig.value?.name ?? 'Redis查询'),
        ),
        actions: [
          IconButton(
            icon: const Icon(Icons.settings),
            onPressed: () {
              Get.to(
                () => RedisConfigPage(
                  config: _redisController.currentConfig.value,
                ),
              );
            },
          ),
        ],
      ),
      body: Column(
        children: [
          // 状态区卡片美化
          Obx(() {
            final config = _redisController.currentConfig.value;
            final isConnected = config?.isConnected ?? false;
            final connectStatusColor = isConnected
                ? themeController.primaryColor.value
                : themeController.primaryColor.value.withAlpha(100);
            return Card(
              margin: const EdgeInsets.fromLTRB(0, 0, 0, 6),
              elevation: 0,
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(0),
              ),
              child: Padding(
                padding: const EdgeInsets.symmetric(
                  horizontal: 12,
                  vertical: 4,
                ),
                child: Row(
                  children: [
                    Icon(
                      isConnected ? Icons.link : Icons.link_off,
                      color: connectStatusColor,
                      size: 20,
                    ),
                    const SizedBox(width: 10),
                    Text(
                      config == null ? '未选择配置' : (isConnected ? '已连接' : '未连接'),
                      style: TextStyle(
                        color: connectStatusColor,
                        fontWeight: FontWeight.w600,
                        fontSize: 14,
                      ),
                    ),
                    const Spacer(),
                    if (config != null)
                      ElevatedButton.icon(
                        style: ElevatedButton.styleFrom(
                          backgroundColor: connectStatusColor,
                          foregroundColor: Colors.white,
                          minimumSize: const Size(80, 36),
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(6),
                          ),
                          elevation: 0,
                        ),
                        onPressed: () {
                          if (isConnected) {
                            _redisController.disconnect();
                          } else {
                            _redisController.connect(config);
                          }
                        },
                        icon: Icon(
                          isConnected ? Icons.link_off : Icons.link,
                          size: 14,
                        ),
                        label: Text(
                          isConnected ? '点击断开' : '点击连接',
                          style: TextStyle(fontSize: 12),
                        ),
                      ),
                  ],
                ),
              ),
            );
          }),
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
            child: Obx(() {
              final config = _redisController.currentConfig.value;
              final isConnected = config?.isConnected ?? false;
              final connectStatusColor = isConnected
                  ? themeController.primaryColor.value
                  : themeController.primaryColor.value.withAlpha(100);
              return Row(
                children: [
                  Expanded(
                    child: Container(
                      decoration: BoxDecoration(
                        color: Colors.grey[100],
                        borderRadius: BorderRadius.circular(6),
                      ),
                      child: TextField(
                        controller: _searchController,
                        style: const TextStyle(fontSize: 15),
                        decoration: InputDecoration(
                          hintText: '输入要搜索的 key',
                          isDense: true,
                          prefixIcon: const Icon(Icons.search, size: 18),
                          suffixIcon: _searchController.text.isNotEmpty
                              ? IconButton(
                                  onPressed: () {
                                    _searchController.clear();
                                  },
                                  icon: const Icon(Icons.clear, size: 18),
                                )
                              : null,
                          border: InputBorder.none,
                          contentPadding: const EdgeInsets.symmetric(
                            horizontal: 8,
                            vertical: 10,
                          ),
                        ),
                        onSubmitted: (_) => search(),
                      ),
                    ),
                  ),
                  const SizedBox(width: 10),
                  ElevatedButton(
                    onPressed: search,
                    style: ElevatedButton.styleFrom(
                      backgroundColor: connectStatusColor,
                      foregroundColor: Colors.white,
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(6),
                      ),
                      elevation: 0,
                      minimumSize: const Size(80, 40),
                    ),
                    child: const Text('搜索Key', style: TextStyle(fontSize: 15)),
                  ),
                ],
              );
            }),
          ),
          Text('搜索结果', textAlign: TextAlign.left),
          Expanded(
            child: Obx(() {
              if (_redisController.isLoading.value) {
                return const Center(child: CircularProgressIndicator());
              }
              final results = _redisController.searchResults;
              if (results.isEmpty) {
                return const Center(
                  child: Text(
                    '无数据',
                    style: TextStyle(color: Colors.grey, fontSize: 15),
                  ),
                );
              }
              return ListView.separated(
                padding: const EdgeInsets.symmetric(
                  horizontal: 12,
                  vertical: 6,
                ),
                itemCount: results.length,
                itemBuilder: (context, index) {
                  return Card(
                    margin: const EdgeInsets.symmetric(vertical: 4),
                    elevation: 1,
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(6),
                    ),
                    child: ListTile(
                      title: Text(
                        results[index],
                        style: const TextStyle(
                          fontSize: 15,
                          fontWeight: FontWeight.w500,
                        ),
                        overflow: TextOverflow.ellipsis,
                      ),
                      minTileHeight: 38,
                      contentPadding: const EdgeInsets.symmetric(
                        horizontal: 16,
                        vertical: 2,
                      ),
                      onTap: () async {
                        var value = await _redisController.get(results[index]);
                        if (value != null) {
                          print("读取成功: $value");
                          JsonView.string(value);
                          Get.toNamed(AppRoutes.queryResult, arguments: value);
                        } else {
                          print("读取失败");
                        }
                      },
                    ),
                  );
                },
                separatorBuilder: (context, index) => const SizedBox(height: 0),
              );
            }),
          ),
        ],
      ),
    );
  }
}
